package com.yunjian.core.api;

import java.util.Date;
import java.util.Properties;

import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunjian.common.utils.Constant;
import com.yunjian.common.utils.JsonUtil;
import com.yunjian.common.utils.LanguageUtils;
import com.yunjian.core.dto.AccountDto;
import com.yunjian.core.dto.ResponseDto;
import com.yunjian.core.entity.Account;
import com.yunjian.core.entity.EmailCode;
import com.yunjian.core.service.IAccountService;
import com.yunjian.core.service.IEmailCodeService;

import io.swagger.annotations.Api;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

@Api("用户账号与登录相关接口")
@RestController
@RequestMapping("/app/account")
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IEmailCodeService emailCodeServiceImpl;

    @Autowired
    private IAccountService accountServiceImpl;

    /**
     * 获取邮箱验证码
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/getEmailCode", method = RequestMethod.POST)
    @ResponseBody
    public ResponseDto getEmailCode(@RequestBody Account param) {
        logger.info("获取邮箱验证码{}", JsonUtil.toJsonString(param));
        if (StringUtils.isEmpty(param.getEmail())) {
            return new ResponseDto(Constant.FAIL_CODE, null, LanguageUtils.getValueByKey("email.cannot.empty"));
        }
        return emailCodeServiceImpl.sendEmailCode(param);
    }

    /**
     * 用户注册
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ResponseDto register(@RequestBody AccountDto param) {
        logger.info("用户注册{}", JsonUtil.toJsonString(param));
        /*if (StringUtils.isEmpty(param.getEmail()) || StringUtils.isEmpty(param.getPassword())
                || StringUtils.isEmpty(param.getSerialNo()) || StringUtils.isEmpty(param.getCode())) {
            return new ResponseDto(Constant.PARMS_ERROR_CODE, null, LanguageUtils.getValueByKey("system.param.error"));
        }*/
        if (StringUtils.isEmpty(param.getEmail())) {
            return new ResponseDto(Constant.PARMS_ERROR_CODE, null, LanguageUtils.getValueByKey("email.cannot.empty"));
        }else if(StringUtils.isEmpty(param.getPassword())){
            return new ResponseDto(Constant.PARMS_ERROR_CODE, null, LanguageUtils.getValueByKey("password.cannot.empty"));
        }else if (StringUtils.isEmpty(param.getSerialNo())) {
            return new ResponseDto(Constant.PARMS_ERROR_CODE, null, LanguageUtils.getValueByKey("serialNo.isNull"));
        } else if (StringUtils.isEmpty(param.getCode())) {
            return new ResponseDto(Constant.PARMS_ERROR_CODE, null, LanguageUtils.getValueByKey("code.isNull"));
        }
        return accountServiceImpl.register(param);
    }

    /**
     * 用户登录
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseDto login(@RequestBody Account param) {
        logger.info("用户登录{}", JsonUtil.toJsonString(param));
        if (StringUtils.isEmpty(param.getEmail())) {
            return new ResponseDto(Constant.FAIL_CODE, null, LanguageUtils.getValueByKey("email.cannot.empty"));
        }
        if (StringUtils.isEmpty(param.getPassword())){
            return new ResponseDto(Constant.FAIL_CODE, null, LanguageUtils.getValueByKey("password.cannot.empty"));
        }
        return accountServiceImpl.login(param);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public ResponseDto logout() {
        return accountServiceImpl.logout();
    }

    /**
     * 重置密码前校验验证码
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/checkVerifyCode", method = RequestMethod.POST)
    @ResponseBody
    public ResponseDto checkVerifyCode(@RequestBody AccountDto param) {
        logger.info("重置密码前校验验证码{}", JsonUtil.toJsonString(param));
        if (StringUtils.isEmpty(param.getEmail()) || StringUtils.isEmpty(param.getCode())) {
            return new ResponseDto(Constant.FAIL_CODE, null, LanguageUtils.getValueByKey("email.code.isNull"));
        }
        try {
            EmailCode emalCode = emailCodeServiceImpl.getOne(new QueryWrapper<EmailCode>().eq("code", param.getCode())
                    .eq("email", param.getEmail()).eq("delete_flag", 1).gt("expire_time", new Date()));
            if (emalCode != null) {
                // 删除验证码
                emailCodeServiceImpl.remove(new QueryWrapper<EmailCode>().eq("id", emalCode.getId()));
                return new ResponseDto(Constant.SUCCESS_CODE, null, "验证码校验通过");
            } else {
                return new ResponseDto(Constant.FAIL_CODE, null, LanguageUtils.getValueByKey("email.wrong.code"));
            }
        } catch (Exception e) {
            logger.error("验证码校验发生异常", e);
            return new ResponseDto(Constant.FAIL_CODE, null, LanguageUtils.getValueByKey("verify.code.error"));
        }
    }

    /**
     * 重置密码
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
    @ResponseBody
    public ResponseDto resetPassword(@RequestBody AccountDto param) {
        logger.info("重置密码{}", JsonUtil.toJsonString(param));
        if (StringUtils.isEmpty(param.getEmail())) {
            return new ResponseDto(Constant.PARMS_ERROR_CODE, null, LanguageUtils.getValueByKey("email.cannot.empty"));
        } else if(StringUtils.isEmpty(param.getPassword())){
            return new ResponseDto(Constant.PARMS_ERROR_CODE, null, LanguageUtils.getValueByKey("password.cannot.empty"));
        } else if (StringUtils.isEmpty(param.getCode())) {
            return new ResponseDto(Constant.PARMS_ERROR_CODE, null, LanguageUtils.getValueByKey("code.isNull"));
        }
        return accountServiceImpl.resetPassword(param);
    }

    /**
     * 测试发送邮件
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/testSendEmail", method = RequestMethod.POST)
    @ResponseBody
    public ResponseDto testSendEmail(@RequestBody Account param) {
        logger.info("测试发送邮件{}", JsonUtil.toJsonString(param));
        if (StringUtils.isEmpty(param.getEmail())) {
            return new ResponseDto(Constant.FAIL_CODE, null, LanguageUtils.getValueByKey("email.isNull"));
        }
        testSendMail(param.getEmail());
        //sendMail(param.getEmail());
        return new ResponseDto(Constant.SUCCESS_CODE, null, Constant.SUCCESS_MESSAGE);
    }

    private void testSendMail(String email){
        try {
            //设置发件人
            String from = "zwx13148701472@163.com";
            //设置收件人
            String to = email;
            //设置邮件发送的服务器，这里为163邮件服务器
            String host = "smtp.163.com";
            //获取系统属性
            Properties properties = System.getProperties();

            //SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);

            //设置系统属性
            properties.setProperty("mail.smtp.host", host);
            properties.put("mail.smtp.auth", "true");

            //获取发送邮件会话、获取第三方登录授权码
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from, "0755020b");
                }
            });
            session.setDebug(true);

            Message message = new MimeMessage(session);

            //防止邮件被当然垃圾邮件处理，披上Outlook的马甲
            message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");

            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(from));//设置抄送人
            message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));//设置接收人

            //邮件标题
            message.setSubject("This is the subject line!");

            BodyPart bodyPart = new MimeBodyPart();

            bodyPart.setText("我发送了文件给你");

            Multipart multipart = new MimeMultipart();

            multipart.addBodyPart(bodyPart);

            message.setContent(multipart);

            Transport.send(message);
            System.out.println("mail transports successfully");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendMail(String to) {
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", "smtp.163.com");//设置邮件服务器主机名
        props.put("mail.smtp.host", "smtp.163.com");
        props.put("mail.smtp.auth", "true");//发送服务器需要身份验证
        Session session = Session.getDefaultInstance(props);//设置环境信息
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);
        Multipart multipart = null;
        BodyPart contentPart = null;
        Transport transport = null;
        try {
            String from = "zwx13148701472@163.com";
            message.setFrom(new InternetAddress(from));//设置发件人
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(from));//设置抄送人
            message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));//设置接收人
            message.setSubject("发送验证码");
            multipart = new MimeMultipart();//设置附件
            contentPart = new MimeBodyPart();
            contentPart.setContent("验证码为：123456", "text/html;charset=utf-8");
            multipart.addBodyPart(contentPart);
            message.setContent(multipart);
            message.saveChanges();
            transport = session.getTransport("smtp");
            transport.connect("smtp.163.com", "zwx13148701472@163.com", "0755020b");
            transport.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {
            e.printStackTrace();
        }finally {
            try {
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }



    }

}
